<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item>
          <el-card shadow="never" style="width: 1425px">
            <el-button type="primary" @click="handleQuery">
              <template #icon>
                <Search/>
              </template>
              搜索
            </el-button>
            <el-button @click="handleResetQuery">
              <template #icon>
                <Refresh/>
              </template>
              重置
            </el-button>
          </el-card>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button
          v-hasPerm="['system:bigcap:add']"
          type="success"
          @click="handleOpenDialog()"
        >
          <template #icon><Plus /></template>
          新增
        </el-button>
        <el-button
          v-hasPerm="['system:bigcap:delete']"
          type="danger"
          :disabled="removeIds.length === 0"
          @click="handleDelete()"
        >
          <template #icon><Delete /></template>
          删除
        </el-button>

        <!-- 新增Excel操作按钮 -->
        <el-button
          type="primary"
          @click="handleExportExcel()"
        >
          <template #icon><Download /></template>
          导出Excel
        </el-button>
        <el-button
          type="primary"
          @click="handleImportExcel()"
        >
          <template #icon><Upload /></template>
          导入Excel
        </el-button>
        <!-- <el-button
          type="info"
          @click="handleDownloadTemplate()"
        >
          <template #icon><Document /></template>
          下载模板
        </el-button> -->
      </div>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="pageData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          key="id"
          label="主键ID"
          prop="id"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="date"
          label="日期"
          prop="date"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="trafficIndex"
          label="流量指数"
          prop="trafficIndex"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="trafficIndexYoy"
          label="流量指数同比(年)"
          prop="trafficIndexYoy"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="visitorIndex"
          label="访客指数"
          prop="visitorIndex"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="visitorIndexYoy"
          label="访客指数同比(年)"
          prop="visitorIndexYoy"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="followers"
          label="关注人数"
          prop="followers"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="followersYoy"
          label="关注人数同比(年)"
          prop="followersYoy"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="addToCart"
          label="加购人数"
          prop="addToCart"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="addToCartYoy"
          label="加购人数同比(年)"
          prop="addToCartYoy"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="categorySearchIndex"
          label="类目搜索指数"
          prop="categorySearchIndex"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="categorySearchIndexYoy"
          label="类目搜索指数同比(年)"
          prop="categorySearchIndexYoy"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="categoryClickIndex"
          label="类目点击指数"
          prop="categoryClickIndex"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="categoryClickIndexYoy"
          label="类目点击指数同比(年)"
          prop="categoryClickIndexYoy"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="clickRate"
          label="搜索点击率"
          prop="clickRate"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="clickRateYoy"
          label="搜索点击率同比(年)"
          prop="clickRateYoy"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="transactionAmountIndex"
          label="成交金额指数"
          prop="transactionAmountIndex"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="transactionAmountIndexYoy"
          label="成交金额指数同比(年)"
          prop="transactionAmountIndexYoy"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="transactionVolumeIndex"
          label="成交件数指数"
          prop="transactionVolumeIndex"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="transactionVolumeIndexYoy"
          label="成交件数指数同比(年)"
          prop="transactionVolumeIndexYoy"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="conversionRate"
          label="成交转化率"
          prop="conversionRate"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="conversionRateYoy"
          label="成交转化率同比(年)"
          prop="conversionRateYoy"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="customerPrice"
          label="成交客单价"
          prop="customerPrice"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="customerPriceYoy"
          label="成交客单价同比(年)"
          prop="customerPriceYoy"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="brandCount"
          label="品牌数"
          prop="brandCount"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="brandCountYoy"
          label="品牌数同比(年)"
          prop="brandCountYoy"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="visitedBrandCount"
          label="被访问品牌数"
          prop="visitedBrandCount"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="visitedBrandCountYoy"
          label="被访问品牌数同比(年)"
          prop="visitedBrandCountYoy"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="activeBrandCount"
          label="动销品牌数"
          prop="activeBrandCount"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="activeBrandCountYoy"
          label="动销品牌数同比(年)"
          prop="activeBrandCountYoy"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="storeCount"
          label="店铺数"
          prop="storeCount"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="storeCountYoy"
          label="店铺数同比(年)"
          prop="storeCountYoy"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="visitedStoreCount"
          label="被访问店铺数"
          prop="visitedStoreCount"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="visitedStoreCountYoy"
          label="被访问店铺数同比(年)"
          prop="visitedStoreCountYoy"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="activeStoreCount"
          label="动销店铺数"
          prop="activeStoreCount"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="activeStoreCountYoy"
          label="动销店铺数同比(年)"
          prop="activeStoreCountYoy"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="visitedProductCount"
          label="被访问商品数"
          prop="visitedProductCount"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="visitedProductCountYoy"
          label="被访问商品数同比(年)"
          prop="visitedProductCountYoy"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="activeProductCount"
          label="动销商品数"
          prop="activeProductCount"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="activeProductCountYoy"
          label="动销商品数同比(年)"
          prop="activeProductCountYoy"
          min-width="150"
          align="center"
        />
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button
              v-hasPerm="['system:bigcap:edit']"
              type="primary"
              size="small"
              link
              @click="handleOpenDialog(scope.row.id)"
            >
              <template #icon><Edit /></template>
              编辑
            </el-button>
            <el-button
              v-hasPerm="['system:bigcap:delete']"
              type="danger"
              size="small"
              link
              @click="handleDelete(scope.row.id)"
            >
              <template #icon><Delete /></template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery()"
      />
    </el-card>

    <!-- 大盘底表表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="500px"
      @close="handleCloseDialog"
    >
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
<!--        <el-form-item label="主键ID" prop="id">-->
<!--          <el-input-->
<!--            v-model="formData.id"-->
<!--            placeholder="主键ID"-->
<!--          />-->
<!--        </el-form-item>-->

        <el-form-item label="日期" prop="date">
          <el-date-picker
            class="!w-[240px]"
            v-model="formData.date"
            type="date"
            placeholder="日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item label="流量指数" prop="trafficIndex">
          <el-input
            v-model="formData.trafficIndex"
            placeholder="流量指数"
          />
        </el-form-item>

        <el-form-item label="流量指数同比(年)" prop="trafficIndexYoy">
          <el-input
            v-model="formData.trafficIndexYoy"
            placeholder="流量指数同比(年)"
          />
        </el-form-item>

        <el-form-item label="访客指数" prop="visitorIndex">
          <el-input
            v-model="formData.visitorIndex"
            placeholder="访客指数"
          />
        </el-form-item>

        <el-form-item label="访客指数同比(年)" prop="visitorIndexYoy">
          <el-input
            v-model="formData.visitorIndexYoy"
            placeholder="访客指数同比(年)"
          />
        </el-form-item>

        <el-form-item label="关注人数" prop="followers">
          <el-input
            v-model="formData.followers"
            placeholder="关注人数"
          />
        </el-form-item>

        <el-form-item label="关注人数同比(年)" prop="followersYoy">
          <el-input
            v-model="formData.followersYoy"
            placeholder="关注人数同比(年)"
          />
        </el-form-item>

        <el-form-item label="加购人数" prop="addToCart">
          <el-input
            v-model="formData.addToCart"
            placeholder="加购人数"
          />
        </el-form-item>

        <el-form-item label="加购人数同比(年)" prop="addToCartYoy">
          <el-input
            v-model="formData.addToCartYoy"
            placeholder="加购人数同比(年)"
          />
        </el-form-item>

        <el-form-item label="类目搜索指数" prop="categorySearchIndex">
          <el-input
            v-model="formData.categorySearchIndex"
            placeholder="类目搜索指数"
          />
        </el-form-item>

        <el-form-item label="类目搜索指数同比(年)" prop="categorySearchIndexYoy">
          <el-input
            v-model="formData.categorySearchIndexYoy"
            placeholder="类目搜索指数同比(年)"
          />
        </el-form-item>

        <el-form-item label="类目点击指数" prop="categoryClickIndex">
          <el-input
            v-model="formData.categoryClickIndex"
            placeholder="类目点击指数"
          />
        </el-form-item>

        <el-form-item label="类目点击指数同比(年)" prop="categoryClickIndexYoy">
          <el-input
            v-model="formData.categoryClickIndexYoy"
            placeholder="类目点击指数同比(年)"
          />
        </el-form-item>

        <el-form-item label="搜索点击率" prop="clickRate">
          <el-input
            v-model="formData.clickRate"
            placeholder="搜索点击率"
          />
        </el-form-item>

        <el-form-item label="搜索点击率同比(年)" prop="clickRateYoy">
          <el-input
            v-model="formData.clickRateYoy"
            placeholder="搜索点击率同比(年)"
          />
        </el-form-item>

        <el-form-item label="成交金额指数" prop="transactionAmountIndex">
          <el-input
            v-model="formData.transactionAmountIndex"
            placeholder="成交金额指数"
          />
        </el-form-item>

        <el-form-item label="成交金额指数同比(年)" prop="transactionAmountIndexYoy">
          <el-input
            v-model="formData.transactionAmountIndexYoy"
            placeholder="成交金额指数同比(年)"
          />
        </el-form-item>

        <el-form-item label="成交件数指数" prop="transactionVolumeIndex">
          <el-input
            v-model="formData.transactionVolumeIndex"
            placeholder="成交件数指数"
          />
        </el-form-item>

        <el-form-item label="成交件数指数同比(年)" prop="transactionVolumeIndexYoy">
          <el-input
            v-model="formData.transactionVolumeIndexYoy"
            placeholder="成交件数指数同比(年)"
          />
        </el-form-item>

        <el-form-item label="成交转化率" prop="conversionRate">
          <el-input
            v-model="formData.conversionRate"
            placeholder="成交转化率"
          />
        </el-form-item>

        <el-form-item label="成交转化率同比(年)" prop="conversionRateYoy">
          <el-input
            v-model="formData.conversionRateYoy"
            placeholder="成交转化率同比(年)"
          />
        </el-form-item>

        <el-form-item label="成交客单价" prop="customerPrice">
          <el-input
            v-model="formData.customerPrice"
            placeholder="成交客单价"
          />
        </el-form-item>

        <el-form-item label="成交客单价同比(年)" prop="customerPriceYoy">
          <el-input
            v-model="formData.customerPriceYoy"
            placeholder="成交客单价同比(年)"
          />
        </el-form-item>

        <el-form-item label="品牌数" prop="brandCount">
          <el-input
            v-model="formData.brandCount"
            placeholder="品牌数"
          />
        </el-form-item>

        <el-form-item label="品牌数同比(年)" prop="brandCountYoy">
          <el-input
            v-model="formData.brandCountYoy"
            placeholder="品牌数同比(年)"
          />
        </el-form-item>

        <el-form-item label="被访问品牌数" prop="visitedBrandCount">
          <el-input
            v-model="formData.visitedBrandCount"
            placeholder="被访问品牌数"
          />
        </el-form-item>

        <el-form-item label="被访问品牌数同比(年)" prop="visitedBrandCountYoy">
          <el-input
            v-model="formData.visitedBrandCountYoy"
            placeholder="被访问品牌数同比(年)"
          />
        </el-form-item>

        <el-form-item label="动销品牌数" prop="activeBrandCount">
          <el-input
            v-model="formData.activeBrandCount"
            placeholder="动销品牌数"
          />
        </el-form-item>

        <el-form-item label="动销品牌数同比(年)" prop="activeBrandCountYoy">
          <el-input
            v-model="formData.activeBrandCountYoy"
            placeholder="动销品牌数同比(年)"
          />
        </el-form-item>

        <el-form-item label="店铺数" prop="storeCount">
          <el-input
            v-model="formData.storeCount"
            placeholder="店铺数"
          />
        </el-form-item>

        <el-form-item label="店铺数同比(年)" prop="storeCountYoy">
          <el-input
            v-model="formData.storeCountYoy"
            placeholder="店铺数同比(年)"
          />
        </el-form-item>

        <el-form-item label="被访问店铺数" prop="visitedStoreCount">
          <el-input
            v-model="formData.visitedStoreCount"
            placeholder="被访问店铺数"
          />
        </el-form-item>

        <el-form-item label="被访问店铺数同比(年)" prop="visitedStoreCountYoy">
          <el-input
            v-model="formData.visitedStoreCountYoy"
            placeholder="被访问店铺数同比(年)"
          />
        </el-form-item>

        <el-form-item label="动销店铺数" prop="activeStoreCount">
          <el-input
            v-model="formData.activeStoreCount"
            placeholder="动销店铺数"
          />
        </el-form-item>

        <el-form-item label="动销店铺数同比(年)" prop="activeStoreCountYoy">
          <el-input
            v-model="formData.activeStoreCountYoy"
            placeholder="动销店铺数同比(年)"
          />
        </el-form-item>

        <el-form-item label="被访问商品数" prop="visitedProductCount">
          <el-input
            v-model="formData.visitedProductCount"
            placeholder="被访问商品数"
          />
        </el-form-item>

        <el-form-item label="被访问商品数同比(年)" prop="visitedProductCountYoy">
          <el-input
            v-model="formData.visitedProductCountYoy"
            placeholder="被访问商品数同比(年)"
          />
        </el-form-item>

        <el-form-item label="动销商品数" prop="activeProductCount">
          <el-input
            v-model="formData.activeProductCount"
            placeholder="动销商品数"
          />
        </el-form-item>

        <el-form-item label="动销商品数同比(年)" prop="activeProductCountYoy">
          <el-input
            v-model="formData.activeProductCountYoy"
            placeholder="动销商品数同比(年)"
          />
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit()">确定</el-button>
          <el-button @click="handleCloseDialog()">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入Excel对话框 -->
    <el-dialog
      v-model="importDialogVisible"
      title="导入Excel"
      width="500px"
      append-to-body
    >
      <el-upload
        ref="uploadRef"
        :auto-upload="false"
        :limit="5"
        :on-exceed="handleExceed"
        :on-change="handleFileChange"
        :on-remove="handleFileRemove"
        :show-file-list="true"
        accept=".xlsx"
        multiple
        drag
      >
        <el-icon class="el-icon--upload"><Upload /></el-icon>
        <div class="el-upload__text">拖拽文件到此处，或 <em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>支持批量上传，最多5个.xlsx格式文件</span>
            <el-button type="primary" link @click="handleDownloadTemplate">下载模板</el-button>
          </div>
        </template>
      </el-upload>
      <div v-if="importResult" class="mt-15">
        <el-alert
          :title="`导入结果: 成功${importResult.validCount}条，失败${importResult.invalidCount}条，总计${importResult.validCount + importResult.invalidCount}条`"
          :type="importResult.invalidCount > 0 ? 'warning' : 'success'"
          show-icon
        />
        <el-collapse v-if="importResult.messageList && importResult.messageList.length > 0" class="mt-10px">
          <el-collapse-item title="错误详情">
            <ul class="error-list">
              <li v-for="(msg, index) in importResult.messageList" :key="index" class="text-red-500">
                {{ msg }}
              </li>
            </ul>
          </el-collapse-item>
        </el-collapse>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="importDialogVisible = false">取 消</el-button>
          <el-button type="primary" :loading="uploadLoading" @click="submitImport">
            批量导入
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
// 导入图标组件
import { Plus, Delete, Search, Refresh, Download, Upload, Document, Edit } from "@element-plus/icons-vue";

import BigcapAPI, {BigcapForm, BigcapPageQuery, BigcapPageVO} from "@/api/system/bigcap.api";

const queryFormRef = ref();
const dataFormRef = ref();

const loading = ref(false);
const removeIds = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<BigcapPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

// 大盘底表表格数据
const pageData = ref<BigcapPageVO[]>([]);

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

// 大盘底表表单数据
const formData = reactive<BigcapForm>({});

// 大盘底表表单校验规则
const rules = reactive({
  id: [
    { required: false, message: "请输入主键ID", trigger: "blur" }
  ],
  date: [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (!value && formData.id) {
          callback(new Error("日期不能为空"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ]
});

/** 查询大盘底表 */
function handleQuery() {
  loading.value = true;
  BigcapAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置大盘底表查询 */
function handleResetQuery() {
  queryFormRef.value!.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/** 打开大盘底表弹窗 */
function handleOpenDialog(id?: number) {
  dialog.visible = true;
  if (id) {
    dialog.title = "修改大盘底表";
    BigcapAPI.getFormData(id).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增大盘底表";
    formData.id = undefined;
    //formData.date = new Date().toISOString().split('T')[0]; // 自动填充今天日期
  }
}

/** 提交大盘底表表单 */
function handleSubmit() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        BigcapAPI.update(id, formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        BigcapAPI.add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭大盘底表弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  formData.id = undefined;
}

/** 删除大盘底表 */
function handleDelete(id?: number) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      BigcapAPI.deleteByIds(ids)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

// 添加导入对话框相关变量
const importDialogVisible = ref(false);
const importFiles = ref<File[]>([]);
const importResult = ref<ExcelResult | null>(null);
const uploadLoading = ref(false);
const uploadRef = ref();

// 导出Excel处理函数
const handleExportExcel = () => {
  BigcapAPI.exportExcel(queryParams).then(res => {
    // 创建a标签并模拟点击下载
    const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' });
    const fileName = `大盘数据_${new Date().getTime()}.xlsx`;
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = fileName;
    link.click();
    URL.revokeObjectURL(link.href);
    ElMessage.success('导出成功');
  }).catch(() => {
    ElMessage.error('导出失败');
  });
};

// 导入Excel处理函数
const handleImportExcel = () => {
  importDialogVisible.value = true;
  importFiles.value = [];
  importResult.value = null;
  if (uploadRef.value) {
    uploadRef.value.clearFiles();
  }
};

// 下载模板处理函数
const handleDownloadTemplate = () => {
  BigcapAPI.downloadTemplate().then(res => {
    const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' });
    const fileName = `大盘数据导入模板.xlsx`;
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = fileName;
    link.click();
    URL.revokeObjectURL(link.href);
    ElMessage.success('模板下载成功');
  }).catch(() => {
    ElMessage.error('模板下载失败');
  });
};

// 文件超出限制回调
const handleExceed = () => {
  ElMessage.warning('最多只能上传5个文件');
};

// 文件状态改变时的回调
const handleFileChange = (file: any) => {
  importFiles.value.push(file.raw);
};

// 文件移除时的回调
const handleFileRemove = (file: any) => {
  const index = importFiles.value.findIndex(f =>
    f.name === file.name && f.size === file.size
  );
  if (index !== -1) {
    importFiles.value.splice(index, 1);
  }
};

// 提交导入
const submitImport = async () => {
  if (importFiles.value.length === 0) {
    ElMessage.warning('请先选择要上传的Excel文件');
    return;
  }

  uploadLoading.value = true;

  try {
    let totalValidCount = 0;
    let totalInvalidCount = 0;
    let allMessages: string[] = [];

    // 依次处理每个文件
    for (const file of importFiles.value) {
      const result = await BigcapAPI.importExcel(file);
      totalValidCount += result.validCount;
      totalInvalidCount += result.invalidCount;
      if (result.messageList) {
        allMessages = allMessages.concat(result.messageList.map(msg => `[${file.name}] ${msg}`));
      }
    }

    // 更新导入结果
    importResult.value = {
      validCount: totalValidCount,
      invalidCount: totalInvalidCount,
      messageList: allMessages,
      success: totalInvalidCount === 0
    };

    if (totalInvalidCount === 0) {
      ElMessage.success(`批量导入成功，共导入${totalValidCount}条数据`);
      // 导入成功后关闭对话框
      setTimeout(() => {
        importDialogVisible.value = false;
      }, 2000);
    } else {
      ElMessage.warning(`导入完成，成功${totalValidCount}条，失败${totalInvalidCount}条`);
    }

    // 刷新表格数据
    handleQuery();
  } catch (error) {
    console.error('导入出错:', error);
    ElMessage.error('导入失败，请检查文件格式是否正确');
  } finally {
    uploadLoading.value = false;
  }
};

onMounted(() => {
  handleQuery();
});
</script>
